// pages/extraInfo/extraInfo.js
var app = getApp()
var host = app.globalData.host
var self = null

Page({
  data: {
    info: null,
    itemId: '',
    productId: '',
    groupId: '',

    count: 1,
    formatId: '',
    userName: '',
    postalCode: '',
    provinceName: '',
    cityName: '',
    countyName: '',
    detailInfo: '',
    nationalCode:'',
    telNumber: '',

    groupArray: ["男子2岁A组", "男子2岁B组", "女子2岁G组", "男子3岁A组", "男子3岁B组", "女子3岁G组", "男子4岁A组", "男子4岁B组", "女子4岁G组", "男子5岁组", "女子5岁组", "Open组"],
    group: '',
    realName: '',
    idNo: '',
    group2: '',
    realName2: '',
    idNo2: '',
    contact: '',
    others: '',

    extra: [],
    extraInfo: [],

    formats: '',
    numbers: [],
    themeColor: '',
    defaultColor: '',
    borderColor: ''
  },
  onLoad: function (options) {
    self = this;
    self.setData({
      itemId: options.itemId ? options.itemId : '',
      productId: options.productId ? options.productId : '',
      groupId: options.groupId ? options.groupId : '',
      formatId: options.formatId ? options.formatId : ''
    })
    self.getStyle();
    self.getNumbers();
    self.getInfo();
  },
  getStyle() {
    self.setData({
      themeColor: app.globalData.themeColor
    })
  },
  getInfo() {
    var url = null;
    var params = null;
    if (self.data.itemId) {
      url = host + '/yq/item/info'
      params = {
        itemId: self.data.itemId
      }
    } else if (self.data.productId) {
      url = host + '/yq/product/info'
      params = {
        productId: self.data.productId
      }
    }
    var success = function (res) {
      console.log(res);
      self.setData({
        info: res.info
      })
      if (!res.info.product) {
        wx.showModal({
          title: '错误',
          content: '找不到商品信息',
          showCancel: false,
          success: function () {
            wx.navigateBack({
              delta: 1
            })
          }
        })
        return;
      }
      if (res.info.product.formats) {
        self.setData({
          // formats: JSON.parse(res.info.product.formats)
          formats: res.info.product.formats
        })
      }
      if (res.info.product.isNeedMoreInfo == 1) {
        self.counter();
      }
      if (res.info.product.extraJson) {
        var extra = JSON.parse(res.info.product.extraJson);
        for (var i = 0; i < extra.length; i ++) {
          if (extra[i].type === 0 || extra[i].type === 1) {
            var options = extra[i].options.split(";");
            options.pop();
            extra[i].options = options;
          }
        }
        self.setData({
          extra: extra
        })
        var extraInfo = new Array(self.data.extra.length);
        for (var i = 0; i < extraInfo.length; i ++) {
          extraInfo[i] = "";
        }
        self.setData({
          extraInfo: extraInfo
        })
      }
      console.log(self.data.extra);
    };
    var fail = function (res) { };
    var complete = function () { };
    app.request(url, params, success, fail, complete);
  },
  getNumbers() {
    var temp = []
    for (var i = 1; i <= 10; i++) {
      temp.push(i)
    }
    self.setData({
      numbers: temp
    })
  },
  address() {
    wx.chooseAddress({
      success: function (res) {
        self.setData({
          userName: res.userName,
          postalCode: res.postalCode,
          provinceName: res.provinceName,
          cityName: res.cityName,
          countyName: res.countyName,
          detailInfo: res.detailInfo,
          nationalCode: res.nationalCode,
          telNumber: res.telNumber,
        })
      }
    })
  },
  decrease() {
    var count = this.data.count
    if (count <= 1) {
      count = 1;
    } else {
      count -= 1;
    }
    this.setData({
      count: count
    })
    self.counter()
  },
  plus() {
    var count = this.data.count
    count += 1;
    this.setData({
      count: count
    })
    self.counter()
  },
  countPickerChange(e) {
    var count = parseInt(e.detail.value)
    self.setData({
      count: count
    })
    self.counter()
  },
  counter() {
    var price = 0;
    if (self.data.formatId) {
      for (var i = 0; i < self.data.formats.length; i ++) {
        if (self.data.formats[i].id == self.data.formatId) {
          price = self.data.formats[i].fee;
          break;
        }
      }
    } else {
      price = self.data.info.product ? self.data.info.product.price.toFixed(2) : 0;
    }
    var count = parseInt(self.data.count)
    var total = price * count
    self.setData({
      total: total
    })
  },

  groupPickerChange(e) {
    self.setData({
      group: self.data.groupArray[e.detail.value]
    })
  },
  realNameChange(e) {
    self.setData({
      realName: e.detail.value
    })
  },
  idNoChange(e) {
    self.setData({
      idNo: e.detail.value
    })
  },
  groupPickerChange2(e) {
    self.setData({
      group2: self.data.groupArray[e.detail.value]
    })
  },
  realNameChange2(e) {
    self.setData({
      realName2: e.detail.value
    })
  },
  idNoChange2(e) {
    self.setData({
      idNo2: e.detail.value
    })
  },
  contactChange(e) {
    self.setData({
      contact: e.detail.value
    })
  },
  othersChange(e) {
    self.setData({
      others: e.detail.value
    })
  },
  getPhoneNumber(e) {
    console.log(e);
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      wx.checkSession({
        success() {
          var url = host + '/yq/auth/getPhoneNumber';
          var params = {
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv
          };
          var success = function (res) {
            self.setData({
              contact: res.info
            })
          }
          var fail = function (res) {
          };
          var complete = function () { };
          app.request(url, params, success, fail, complete);
        },
        fail() {
          // app.loginWechat(this.getPhoneNumber);
        }
      })

    } else {
      wx.showToast({
        title: '获取手机号失败',
        icon: 'none'
      })
    }
  },

  extraPickerChange(e) {
    var index = Number(e.currentTarget.dataset.index);
    var extraInfo = self.data.extraInfo;
    if (self.data.extra[index].type === 0) {
      var optIndex = Number(e.detail.value);
      extraInfo[index] = self.data.extra[index].options[optIndex];
    } else {
      extraInfo[index] = e.detail.value;
    }
    self.setData({
      extraInfo: extraInfo
    })
  },
  onCheckboxChange(e) {
    var index = Number(e.currentTarget.dataset.index);
    var extraInfo = self.data.extraInfo;
    var value = '';
    for (var i = 0; i < e.detail.value.length; i ++) {
      value += e.detail.value[i] + "，";
    }
    value = value.slice(0, -1);
    extraInfo[index] = value;
    self.setData({
      extraInfo: extraInfo
    })
  },
  onTextInput(e) {
    var index = Number(e.currentTarget.dataset.index);
    var extraInfo = self.data.extraInfo;
    extraInfo[index] = e.detail.value;
    self.setData({
      extraInfo: extraInfo
    })
  },
  onSubmit() {
    if (!wx.getStorageSync("openId")) {
      wx.showModal({
        title: '提示',
        content: '还没允许获取用户信息',
        confirmText: '去设置',
        success: function (res) {
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
              }
            })
          }
        }
      })
      return;
    }
    if (self.data.info.product.isNeedMoreInfo === 1 && (!self.data.userName || !self.data.telNumber || !self.data.provinceName)) {
      wx.showToast({
        title: '请填写收货地址',
        icon: 'none'
      })
      return;
    }
    if (self.data.info.product.isNeedMoreInfo === 2) {
      if (!self.data.group) {
        wx.showToast({
          title: '请选择组别',
          icon: 'none'
        })
        return;
      }
      if (!self.data.realName) {
        wx.showToast({
          title: '请填写真实姓名',
          icon: 'none'
        })
        return;
      }
      if (!self.data.idNo) {
        wx.showToast({
          title: '请填写身份证号',
          icon: 'none'
        })
        return;
      }
      if (self.data.idNo.length != 7 && self.data.idNo.length != 8 && self.data.idNo.length != 18) {
        wx.showToast({
          title: '请填写正确的身份证号',
          icon: 'none'
        })
        return;
      }
      if (!self.data.contact) {
        wx.showToast({
          title: '请填写联系电话',
          icon: 'none'
        })
        return;
      }
    }
    if (self.data.info.product.isNeedMoreInfo === 3) {
      if (!self.data.realName) {
        wx.showToast({
          title: '请填写姓名',
          icon: 'none'
        })
        return;
      }
      if (!self.data.contact) {
        wx.showToast({
          title: '请填写联系电话',
          icon: 'none'
        })
        return;
      }
    }

    var remark = '';
    if (self.data.info.product.isNeedMoreInfo == 2) {
      remark = "组别：" + self.data.group + "，真实姓名：" + self.data.realName + "，身份证号：" + self.data.idNo + "，联系电话：" + self.data.contact;

      if (self.data.productId == 20 || self.data.productId == 22 || self.data.productId == 23) {
        if (!self.data.group2) {
          wx.showToast({
            title: '请选择组别',
            icon: 'none'
          })
          return;
        }
        if (!self.data.realName2) {
          wx.showToast({
            title: '请填写真实姓名',
            icon: 'none'
          })
          return;
        }
        if (!self.data.idNo2) {
          wx.showToast({
            title: '请填写身份证号',
            icon: 'none'
          })
          return;
        }
        if (self.data.idNo2.length != 7 && self.data.idNo2.length != 8 && self.data.idNo2.length != 18) {
          wx.showToast({
            title: '请填写正确的身份证号',
            icon: 'none'
          })
          return;
        }
        remark = "参赛者一姓名：" + self.data.realName + "，参赛者一身份证：" + self.data.idNo + "，参赛者一组别：" + self.data.group + "，参赛者二姓名：" + self.data.realName2 + "，参赛者二身份证：" + self.data.idNo2 + "，参赛者二组别：" + self.data.group2 + "，联系电话：" + self.data.contact;
      }
      if (self.data.others) {
        remark += "，备注：" + self.data.others + "；";
      }
    }
    if (self.data.info.product.isNeedMoreInfo == 3) {
      remark = "姓名：" + self.data.realName + "，联系电话：" + self.data.contact + "；";
    }
    for (var i = 0; i < self.data.extra.length; i ++) {
      if (self.data.extra[i].type == 5) { // 跳过分割线
        continue;
      }
      remark += self.data.extra[i].title + "：" + self.data.extraInfo[i] + "；";
    }
    console.log(remark);

    wx.showLoading({
      title: '支付中',
    })
    var url = host + '/yq/order/pay';
    var params = {
      userName: self.data.userName,
      postalCode: self.data.postalCode,
      provinceName: self.data.provinceName,
      cityName: self.data.cityName,
      countyName: self.data.countyName,
      detailInfo: self.data.detailInfo,
      nationalCode: self.data.nationalCode,
      telNumber: self.data.telNumber,
      count: self.data.count,
      formatId: self.data.formatId,
      remark: remark
    }
    if (self.data.productId) {
      params.productId = self.data.productId;
    }
    if (self.data.itemId) {
      params.itemId = self.data.itemId;
    }
    if (self.data.groupId) {
      params.groupId = self.data.groupId;
    }
    var success = function (res) {
      wx.hideLoading()
      var response = res.info
      console.log(response)
      var nonce_str = response.nonce_str
      var prepay_id = response.package
      var sign = response.sign
      var timestamp = response.timeStamp
      var appId = response.appid
      var param = {
        'appId': appId,
        'timeStamp': '' + timestamp,
        'nonceStr': '' + nonce_str,
        'package': 'prepay_id=' + prepay_id,
        'signType': 'MD5',
        'paySign': '' + sign,
        'success': function (res) {
          setTimeout(function () {
            wx.redirectTo({
              url: '/pages/success/success?isFromMore=1'
            })
          }, 200)
        },
        'fail': function (res) {
          wx.showToast({
            title: '支付失败',
            icon: 'none'
          })
        }
      }
      wx.requestPayment(param)
    }
    var fail = function (res) { };
    var complete = function () { };
    app.request(url, params, success, fail, complete);
  }
})